#!/usr/bin/python3

import re
import shutil
import subprocess
import time
import requests
import json

from bili.constants import *
import bili.helper as helper

header0={ "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" }
header={'Referer': 'https://www.bilibili.com'}
header["User-Agent"]=header0["User-Agent"]

class SpiderAid(object):            
    patternPre="\"aid\":"
    patternSuffix=","
    aidPattern=re.compile("{}\d+{}".format(patternPre,patternSuffix))
    patternPre2="\"cid\":"
    patternSuffix2=","
    cidPattern=re.compile("{}\d+{}".format(patternPre2,patternSuffix2))
    
    session=None

    def fetch_vod_play_url(self,aid):
        # http://server.lan:19999/api/onlinevod/from_bili/22668848
        try:
            resp=requests.get("http://v3.tv.server.lan:19999/api/onlinevod/from_bili/"+aid)
            return resp.text
        except:
            return ""
    
    def fetch(self,url):
        if self.session==None:
            self.session=requests.session()
            self.session.get("https://www.bilibili.com/",headers=header0)
        print("[INTERNET] fetch, url=",url)
        res=self.session.get(url,headers=header)
        return res

    def get_aid_cid_by_bvid(self,bvid):
        #curl "http://server.lan:19999/api/onlinevod/from_bili/BV1gG411f7zX/get_bili_aid"
        # aid cid 为纯数字.
        #curl "http://server.lan:19999/api/onlinevod/from_bili/aid"
        # curl "http://server.lan:19999/api/onlinevod/from_bili/aid/cid"
        # curl "http://server.lan:19999/api/onlinevod/from_bili/season_id_33415"
        
        url="https://www.bilibili.com/video/{0}/".format(bvid)
        try:
            text=self.fetch(url).text
            match=self.aidPattern.search(text)
            # print(text)
            aid,cid=None,None
            if match:
                aid=text[match.start()+len(self.patternPre):match.end()-len(self.patternSuffix)]
                match=self.cidPattern.search(text)
                if match:
                    cid=text[match.start()+len(self.patternPre2):match.end()-len(self.patternSuffix2)]
            print("aid,cid=",aid,cid)
            return aid,cid
        except Exception as e:
            print("[W] get aid err",e)
            return None,None
        
    def get_cid_by_aid(self,aid):
        # aid -> 播放列表
        # todo
        return None
        # return self.globalState.aid2cidStore.get(aid)


    def fetch_info_by_aid(self,basedir,aid):
        res={}
        detail_url="https://api.bilibili.com/x/web-interface/view?aid={}".format(aid)
        try:
            detail=self.fetch(detail_url).text
            # print(detail)
            detail_data=json.loads(detail)['data']

            v_type=helper._get_value(detail_data,'tname')
            pic=helper._get_value(detail_data,'pic')
            title=helper._get_value(detail_data,'title')
            owner=helper._get_value(helper._get_value(detail_data,'owner'),"name")
            # count=_get_value(detail_data,'videos') # 视频 数量
            desc=helper._get_value(detail_data,'desc') # 描述
            view=helper._get_value(helper._get_value(detail_data,'stat'),"view") #播放量
            if view:
                try:
                    v=int(view)
                    if v>10000:
                        v=round(v/10000,1)
                        view="播放量:{}w".format(v)
                    else:
                        view="播放量:{}".format(view)
                except Exception as e:
                    print("[W] get viewed count err")
                pass

            self.download_pic(basedir,pic,str(aid),True)

            res={
                "vod_id": aid, #"/tv_others/detail/bili/"+aid,# /tv_others/detail/bili/aid
                "vod_name": title,
                "vod_pic": pic,#"{}.jpg".format(aid),
                "vod_tag" : "file",
                "vod_director":owner,
                "vod_remarks": view,
                "type_name": v_type,
                "vod_content": desc,
            }
            # helper.save_as_json(res,aid) # 保存数据以待加工.
            return res
        except Exception as e:
            print(e)
            return None



    # 裁剪...
    #ffmpeg -i __poster.jpg -vf "scale=500:900:force_original_aspect_ratio=decrease,pad=500:900:(ow-iw)/2:(oh-ih)/2" OUT.jpg
    # 横向 图片 转成 纵向. 扩充 Y 轴. 黑色背景.
    #ffmpeg -i __poster.jpg -vf "scale=720:1280:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)/2" OUT.jpg
    #ffmpeg -i __poster.jpg -vf "scale=500:900:force_original_aspect_ratio=decrease,pad=500:900:(ow-iw)/2:(oh-ih)/2" OUT.jpg
    def download_pic(self,basedir,url,aid,force=False):
        if not url.startswith("http"):
            return False

        image="{}/{}.origin.jpg".format(basedir,aid)
        # 横向 补纵向 !!
        out="{}/{}.jpg".format(basedir,aid)

        if not force and helper._get_file_size(out)>10:
            # 已经存在
            pass
        else:
            res=self.fetch(url) #requests.get(url,headers=header)
            if res.status_code!=200 or not res.content:
                print("[E] download image error")
                return False

            try:
                with open(image,"wb") as f:
                    n=f.write(res.content)
                    print("[I] get poster image success len = ",n)
                    if n==0:
                        return False
                if aid.startswith(SEASON_PREFIX):
                    # 这个本来就是 纵向的!!!
                    # shutil.copyfile(image,out)
                    shutil.move(image,out)
                    return True
                else:
                    # 横向 图片 转成 纵向.
                    #ffmpeg_cmd=["ffmpeg","-nostdin", "-y", "-i", image, "-vf", "scale=500:900:force_original_aspect_ratio=decrease,pad=500:900:(ow-iw)/2:(oh-ih)/2", out]
                    ffmpeg_cmd=["ffmpeg","-nostdin", "-y", "-i", image, "-vf", "scale=300:400:force_original_aspect_ratio=decrease,pad=300:400:(ow-iw)/2:(oh-ih)/2", out]
                    subprocess.run(ffmpeg_cmd,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
                    time.sleep(1)
                    for i in range(8):
                        if helper._get_file_size(out)>0:
                            print("[I] image scalled ")
                            return True
                            # break
                        else:
                            print("[I] image scalling ",i)
                        time.sleep(1)

            except Exception as e:
                print(e)
                print("[E] download poster image error II")
                return False

        return False

